<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type {
  roleData,
  allRoleResponse,
  NemuData,
  allPermissionResponse,
} from '@api/acl/role/type.ts'
import {
  allRoleListAPI,
  addRoleAPI,
  editRoleAPI,
  getPermissionListAPI,
  setPermissionAPI,
  removeRoleAPI
} from '@api/acl/role/index.ts'
import { ElMessage } from 'element-plus'

const pageSize = ref<number>(10)
const currentPage = ref<number>(1)
const total = ref<number>(0)
const roleName = ref<string>('')
const loading = ref<boolean>(false)
const roleList = ref<roleData[]>([])

// 获取列表数据
const getUserInfoListFn = async () => {
  loading.value = true
  const res: allRoleResponse = await allRoleListAPI(
    currentPage.value,
    pageSize.value,
    roleName.value,
  )
  roleList.value = res.data.records
  total.value = res.data.total
  loading.value = false
}
onMounted(() => getUserInfoListFn())
// 分页器
const handleSizeChange = (e: number) => {
  pageSize.value = e
  getUserInfoListFn()
}
const handleCurrentChange = (e: number) => {
  currentPage.value = e
  getUserInfoListFn()
}

const showRoleDialog = ref<boolean>(false)
const titleRoleDialog = ref<string>('')
// 点击添加职位按钮
const handleAddFn = () => {
  titleRoleDialog.value = '添加角色'
  showRoleDialog.value = true
  roleDataObj.value = {
    roleName: '',
  }
}

const roleDataObj = ref<roleData>({})
// 点击编辑按钮
const handleEditBtnFn = (row: roleData) => {
  titleRoleDialog.value = '修改角色'
  showRoleDialog.value = true
  roleDataObj.value = JSON.parse(JSON.stringify(row))
}

// 点击删除按钮
const handleRemoveFn = (row: roleData) => {
  console.log(row)
  removeRoleAPI(row.id as number).then(res => {
    if(res.code === 200) {
      ElMessage.success('删除成功')
      getUserInfoListFn()
    }
  })
}

// 点击确定按钮
const handleConfirmFn = async () => {
  if (!roleDataObj.value.id) {
    // 新增
    await addRoleAPI(roleDataObj.value)
  } else {
    // 编辑
    await editRoleAPI(roleDataObj.value)
  }

  // 更新数据
  getUserInfoListFn()
  showRoleDialog.value = false
}

// 树形控件
// 点击分配权限按钮
const roleId = ref<number>(0)
const handleUserFn = async (row: roleData) => {
  showRoleDrawer.value = true
  const res: allPermissionResponse = await getPermissionListAPI(
    row.id as string,
  )
  console.log(res)
  data.value = res.data
  roleId.value = row.id as number

  // 递归过滤被选中的
  filterSelectFn(res.data)
}
const filterSelectFn = (data: NemuData[]) => {
  data.forEach((item: NemuData) => {
    if(item.select && item.level === 4) {
      checkedKeysArr.value.push(item.id)
    }
    if(item.children && item.children.length > 0) {
      filterSelectFn(item.children)
    }
  })
}

const showRoleDrawer = ref<boolean>(false)
const defaultProps = {
  children: 'children',
  label: 'name',
}
const data = ref<NemuData[]>([])
const checkedKeysArr = ref<(string | number)[]>([])

// 点击确定按钮
let tree = ref(null)
const confirmClick = async () => {
  // 获取被选中的id
  let choseArr = (tree.value as any).getCheckedKeys()
  // 获取被选中数据的父节点的id
  let choseFatherArr = (tree.value as any).getHalfCheckedKeys()
  
  const res = await setPermissionAPI(roleId.value, [...choseArr, ...choseFatherArr] as number[])
  if(res.code === 200) {
    ElMessage.success('分配成功')
    getUserInfoListFn()
    showRoleDrawer.value = false
  }
}

// 点击重置按钮
const handleResetFn = () => {
  roleName.value = ''
  currentPage.value = 1
  getUserInfoListFn()
}

// 点击搜索按钮
const handleSearchFn = () => {
  currentPage.value = 1
  getUserInfoListFn()
}
</script>

<template>
  <div>
    <el-card>
      <el-form inline class="form">
        <el-form-item label="职位搜索">
          <el-input v-model="roleName" placeholder="请输入职位搜索的关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="handleSearchFn">搜索</el-button>
          <el-button size="default" @click="handleResetFn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card style="margin: 20px 0">
      <el-button type="primary" icon="Plus" @click="handleAddFn">
        添加职位
      </el-button>

      <el-table v-loading="loading" :data="roleList" style="margin: 20px 0">
        <el-table-column
          type="index"
          align="center"
          label="#"
          width="80px"
        ></el-table-column>
        <el-table-column
          align="center"
          label="id"
          prop="id"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="roleName"
          align="center"
          label="职位名称"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          align="center"
          label="更新时间"
        ></el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <el-button size="small" icon="User" @click="handleUserFn(row)">
              分配权限
            </el-button>
            <el-button
              size="small"
              icon="Edit"
              type="primary"
              @click="handleEditBtnFn(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              title="是否确认删除该用户"
              @confirm="handleRemoveFn(row)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :small="true"
        :background="true"
        layout="prev, pager, next, jumper, ->, total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加职位弹窗 -->
    <el-dialog v-model="showRoleDialog" :title="titleRoleDialog">
      <el-form :model="roleDataObj">
        <el-form-item props="roleName" label="职位名称">
          <el-input
            v-model="roleDataObj.roleName"
            placeholder="请输入职位名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleConfirmFn">确定</el-button>
        <el-button @click="showRoleDialog = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 角色权限分配抽屉 -->
    <el-drawer v-model="showRoleDrawer">
      <template #header>
        <div>分配权限</div>
      </template>
      <template #default>
        <el-tree
          ref="tree"
          :data="data"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="checkedKeysArr"
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="showRoleDrawer = false">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
}
</style>
